﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows;
using System.Windows.Markup;
using System.Xml;

namespace Drawer.Common
{
    public class Utils
    {
        private static List<Assembly> assemblyList;
        private static string BASE_SHAPE_CLASS = "Drawer.Common.BaseShape";

        public static List<string> GetAllShapeClasses()
        {
            assemblyList = new List<Assembly>();
            string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string shapeLibPath = appPath + "\\ShapeLib";

            if (Directory.Exists(shapeLibPath))
            {
                foreach (string dll in Directory.GetFiles(shapeLibPath, "*.dll"))
                    assemblyList.Add(Assembly.LoadFile(dll));
            }

            List<string> returnList = new List<string>();
            foreach (var asm in assemblyList)
            {
                foreach (Type type in asm.GetTypes())
                {
                    if (type.IsClass && type.BaseType.FullName == BASE_SHAPE_CLASS)
                    {
                        returnList.Add(type.Name);
                    }
                }
            }

            return returnList;
        }

        public static object CreateShapeFromClassName(string className)
        {
            foreach (var asm in assemblyList)
            {
                foreach (Type type in asm.GetTypes())
                {
                    if (type.IsClass && type.BaseType.FullName == BASE_SHAPE_CLASS && type.Name == className)
                    {
                        return Activator.CreateInstance(type);
                    }
                }
            }

            return null;
        }

        public static UIElement CopyUIElement(UIElement element)
        {
            string shapeString = XamlWriter.Save(element);
            StringReader stringReader = new StringReader(shapeString);
            XmlTextReader xmlTextReader = new XmlTextReader(stringReader);
            UIElement objectCopy = (UIElement)XamlReader.Load(xmlTextReader);
            return objectCopy;
        }
    }
}
